package com.day1020;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CopyOnWriteArrayList;

public class FlyPanel extends JPanel {
    //  子弹数组
    public static CopyOnWriteArrayList<Bullet> bulletList = new CopyOnWriteArrayList<>();
    //  敌机数组
    public static CopyOnWriteArrayList<FlySprite> enemys = new CopyOnWriteArrayList<>();
    ImageLoadUtils imageLoadUtils = new ImageLoadUtils();
    public static Hero hero = new Hero();
    //  当前游戏状态
    public static GameState gameState = GameState.STATE;
    //  游戏音乐
    SoundPool bgSoundPool;
    SoundPool shootSoundPool;

    BgRoll bgRoll = null;
    ShootTask shootTask;
    EnemyTask enemyTask;
    HitTask hitTask;
    Timer timer = new Timer();
    BufferedImage background;

    int x,y;
    int bgwidth;
    int bgheight;
    BufferedImage start;
    BufferedImage pause;
    BufferedImage gameover;

    public FlyPanel() {
        background = imageLoadUtils.load("background.png");
        bgwidth = background.getWidth();
        bgheight = background.getHeight();
        start = imageLoadUtils.load("start.png");
        pause = imageLoadUtils.load("pause.png");
        gameover = imageLoadUtils.load("gameover.png");
        //  让当前面板失去焦点  ????????????
        setFocusable(true);
        super.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                //  切换游戏状态   鼠标点击事件
                switch (gameState){
                    case STATE:
                    case PAUSE:
                        gameState = GameState.RUNNING;
                        startGameTask();
                        break;
                    case RUNNING:
                        gameState = GameState.PAUSE;
                        pauseGameTask();
                        repaint();
                        break;
                    case GAME_OVER:
                        gameState = GameState.STATE;
                        repaint();
                        break;
                }
            }
        });
        super.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                //  获取被按下的按键码
                int code = e.getKeyCode();
                hero.move(code);
                /**
                 * 键盘按下空格键，发射子弹
                 */
//                if (code == KeyEvent.VK_SPACE){
//                    hero.shoot();
//                }
            }
        });
        //timer.schedule(new BgRoll(),0,50);  //  背景图片一直滚动
    }

     //  图片滚动
    class BgRoll extends TimerTask{
        @Override
        public void run() {
            //修改y轴的值（制造背景滚动效果）
            y += 5;   //   +5向下滚动，-5向上滚动
            ///   图片的高度1700    窗口高度600
            if (y > 0){
                y = -1100;
            }
            //  重绘
            repaint();
        }
    }

    //  发射子弹
    class ShootTask extends TimerTask{
        @Override
        public void run() {
            hero.shoot();
            //  重绘
            repaint();
        }
    }

    //  发射敌机 和 奖励
    class EnemyTask extends TimerTask{
        @Override
        public void run() {
            Random random = new Random();
            int type = random.nextInt(10);// 生成0到9的随机数
            if (type == 0){// 随机数为0，返回buffAward;否则返回敌机
                BuffAward buffAward = new BuffAward();
                enemys.add(buffAward);
            }else {
                EnemyAirplane enemyAirplane = new EnemyAirplane();
                enemys.add(enemyAirplane);
            }

            repaint();
        }
    }

    //  实时检测是否碰撞任务类
    class HitTask extends TimerTask{
        @Override
        public void run() {
            //  判断是否碰撞
            for (FlySprite enemy : enemys ) {
                if (enemy .isDead()){
                    continue;
                }
                //  是Buff奖励
                if (enemy instanceof BuffAward){
                    continue;
                }
                if (hero.isHit(enemy)){
                    enemy.setDead(true);
                    if (hero.getLife() == 0){
                        //  游戏结束
                        hero.destroy();
                    }else {
                        hero.subtractLife();
                        hero.setDead(true);
                        break;
                    }
                }
            }
            //  子弹与敌机是否碰撞
            for (Bullet bullet : bulletList) {
                for (FlySprite enemy : enemys ) {
                    if (bullet.isHit(enemy)){
                        bullet.destroy();
                        if (enemy instanceof EnemyAirplane){
                            EnemyAirplane enemyAirplane = (EnemyAirplane)enemy;
                            // 减少血量
                            enemyAirplane.setBlood(enemyAirplane.getBlood() - 1);
                            //  判断敌机血槽是否已空
                            if (enemyAirplane.getBlood() == 0){
                                enemy.setDead(true);
                                //播放销毁音效
                                new SoundPool(SoundPool.BOOM).play();
                                hero.setScore(hero.getScore() + enemyAirplane.getScore());
                            }
                        }
                        if (enemy instanceof BuffAward){
                            BuffAward buffAward = (BuffAward)enemy;
                            if (buffAward.getAwardType() == 0){
                                hero.addDoubleFile();
                            }else {
                                hero.addLife();
                            }
                            enemy.destroy();
                        }
                    }
                }
            }
        }
    }

     //   画游戏状态
    public void paintGameState(Graphics g){
        switch (gameState){
            case STATE:
                g.drawImage(start,0,0,null);
                break;
            case PAUSE:
                g.drawImage(pause,0,0,null);
                break;
            case GAME_OVER:
                g.drawImage(gameover,0,0,null);
                break;
        }
    }

    /**
     * 画出生命值和分数
     * @param g
     */
    private void paintLifeAndScore(Graphics g){
        g.setColor(new Color(0xff0000));
        g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,20));
        g.drawString("LIFE." + hero.getLife(),20,45);
        g.drawString("SCORE." + hero.getScore(),20,25);
    }

    /**
     * 根据当前的游戏状态进行绘制图片
     * @param g
     */
    private void paintState(Graphics g){
        switch (gameState){
            case STATE:
                g.drawImage(start,0,0,null);
                break;
            case PAUSE:
                g.drawImage(pause,0,0,null);
                break;
            case GAME_OVER:
                //清理现场 游戏内容的重置
                hero = new Hero();
                enemys.clear();
                bulletList.clear();
                pauseGameTask();
                g.drawImage(gameover,0,0,null);
                break;
        }
    }

    @Override  ///  画笔类
    public void paint(Graphics g) {
        g.drawImage(background,x,y,bgwidth,bgheight,null);
        paintGameState(g);
        hero.draw(g);
        for (Bullet bullet : bulletList) {
            bullet.draw(g);
            bullet.up();
        }
        for (FlySprite enemyAirplane : enemys) {
            enemyAirplane.draw(g);
            //if (enemyAirplane instanceof ActionSprite){
                ActionSprite actionSprite = (ActionSprite)enemyAirplane;
                actionSprite.down();
           // }
        }
        paintLifeAndScore(g);
    }

    /**
     *  优化定时器
     *  startGameTask()  开始游戏
     *  pauseGameTask()  暂停游戏
     */
    public void startGameTask(){
        bgRoll = new BgRoll();
        shootTask = new ShootTask();
        enemyTask = new EnemyTask();
        hitTask = new HitTask();
        timer.schedule(bgRoll,0,50);
        timer.schedule(shootTask,0,300);
        timer.schedule(enemyTask,0,2000);
        timer.schedule(hitTask,0,50);
        bgSoundPool = new SoundPool(SoundPool.BG_MUSIC);
        bgSoundPool.loop();
        shootSoundPool = new SoundPool(SoundPool.SHOOT);
        shootSoundPool.loop();
    }
    public void pauseGameTask(){
        bgRoll.cancel();
        shootTask.cancel();
        enemyTask.cancel();
        hitTask.cancel();
        bgSoundPool.stopAc();
        shootSoundPool.stopAc();
    }

}
